use strict;
use warnings;
use Linux::Input::Wiimote;
require RPC::XML;
require RPC::XML::Client;

sub delete_temp_file {
	chomp(my $home=`echo ~/`); 
	my $temp_file = "$home.qlive/conference/Tmp_RemoteIsConnected.qlive";
	unlink($temp_file);
	return $temp_file
}

sub get_device_id {
	my $wii = shift;
	my $dev = $wii->wiimote_discover();
	print $dev;
	if ($dev eq 0){
		print "Not found device, exit now\n";
		#exit(0);
	}else{ print "Found dev $dev"; }
	return $dev;
}

sub connect_device {
	my $wii = shift;
	my $dev = 0;
	while ($dev eq 0){
		print "Press 1+2 ...\n";
		$dev = get_device_id($wii);
	}
	$wii->wiimote_connect("00:1$dev");
}

sub create_temp_file {
	my $temp_file = shift;
	open(DAT,">$temp_file");
	close(DAT);

	print("create $temp_file\n");
}

sub main {
	print("remote control ...\n");

	my $cli = RPC::XML::Client->new("http://localhost:19191");
	my $wii = new Linux::Input::Wiimote;
	my $temp_file = delete_temp_file();

	
	connect_device($wii);
	create_temp_file($temp_file);
	
	while (1){
		my $status = $wii->wiimote_update();
		print "status = $status\n";

		my $keys = "RELEASE";
		if($wii->get_wiimote_keys_down && $wii->get_wiimote_keys_b){
			$keys = "B-DOWN";
		}elsif ($wii->get_wiimote_keys_up && $wii->get_wiimote_keys_b){
			$keys = "B-UP";		
		}elsif ($wii->get_wiimote_keys_left && $wii->get_wiimote_keys_b){
			$keys = "B-LEFT";
		}elsif ($wii->get_wiimote_keys_right && $wii->get_wiimote_keys_b){
			$keys = "B-RIGHT";	
		}elsif ($wii->get_wiimote_keys_a && $wii->get_wiimote_keys_b){
			$keys = "B-A";
		}elsif($wii->get_wiimote_keys_down()){
			$keys = "DOWN";
		}elsif ($wii->get_wiimote_keys_right()){
			$keys = "RIGHT";
		}elsif ($wii->get_wiimote_keys_up()){
			$keys = "UP";
		}elsif ($wii->get_wiimote_keys_left()){
			$keys = "LEFT";
		}elsif ($wii->get_wiimote_keys_a()){
			$keys = "A";
		}elsif ($wii->get_wiimote_keys_b()){
			$keys = "B";
		}elsif ($wii->get_wiimote_keys_1()){
			$keys = "1";
		}elsif ($wii->get_wiimote_keys_2()){
			$keys = "2";
		}elsif ($wii->get_wiimote_keys_home()){
			$keys = "HOME";
		}elsif ($wii->get_wiimote_keys_minus()){
			$keys = "MINUS";
		}elsif ($wii->get_wiimote_keys_plus()){
			$keys = "PLUS";
		}else {
			$keys = "RELEASE";
		}
	
		print "wearetherock ok $keys\n";
		$cli->send_request("updateState", $keys);
	}
}

# start here
main();
